<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input  placeholder="请输入搜索内容" v-model="queryInfo.query" clearable  @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" border  stripe  style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile"label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column  label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state" @change="usestateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column  label="操作" width="180px">
          <template slot-scope="scope">
            <!--修改-->
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
            </el-tooltip>
            <!--删除-->
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
            </el-tooltip>
            <!--分配角色-->
            <el-tooltip effect="dark" content="角色分配" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini"
              @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[3, 5, 10, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--增加用户操作-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules"  ref="addFormRef"
               label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!--分配角色对话框-->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible"
               width="50%" @close="setRoleDialogClosed">
      <!--内容主体区域-->
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const tempuserList=[
    {
    id:1,
    username:'張三1',
    email:'sfdfa@124.com',
    mobile:'12333333',
    role_name: 'sys',
    mg_state:true
    },{
    id:1,
    username:'張三2',
    email:'sfdfa@124.com',
    mobile:'12333333',
    role_name: 'sys',
    mg_state:true
    },{
    id:1,
    username:'張三3',
    email:'sfdfa@124.com',
    mobile:'12333333',
    role_name: 'sys',
    mg_state:false
  },{
    id:1,
    username:'張三4',
    email:'sfdfa@124.com',
    mobile:'12333333',
    role_name: 'sys',
    mg_state:true
  },{
    id:1,
    username:'張三5',
    email:'sfdfa@124.com',
    mobile:'12333333',
    role_name: 'sys',
    mg_state:false
  }]


    export default {
      name: "Users",
      data(){
        //定义邮箱的校验规则,正则表达式
        var checkEmail=(rule,value,callback)=>{
          const regEmail= /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/
          if(regEmail.test(value)){
            return callback()
          }
          callback(new Error('请输入合适的邮箱'))
        }
        var checkMobile=(rule,value,callback)=>{
          const regMobile= /^[1][3,4,5,7,8][0-9]{9}$/
          if(regMobile.test(value)){
            return callback()
          }
          callback(new Error('请输入合适的手机号码'))
        }
        return {
        //  获取用户列表的参数对象
         queryInfo:{
           query: '',
           //当前在页码
           pageNum: 1,
           //当前每页显示多少条相间
           pageSize: 3
         },
          userList:[],
          total:0,
          //控制添加用户的显示和隐藏
          addDialogVisible: false,
          //添加用户的表单数据
          addForm:{
           username:'',
            password:'',
            email:'',
            mobile:''
          },
          //添加用户表单的验证用户对象
          addFormRules: {
           username:[
              {required: true,message:'请输入用户名',trigger:'blur'},
              {min:3,max:10,message:'用户名长度在3-10之间',trigger:'blur'}
            ],
            password:[
              {required: true,message:'请输入密码',trigger:'blur'},
              {min:6,max:10,message:'用户名长度在6-10之间',trigger:'blur'}
            ],
            email:[
              {required: true,message:'请输入邮箱',trigger:'blur'},
              {validator: checkEmail,trigger:'blur'}
            ],
            mobile:[
              {required: true,message:'请输入手机',trigger:'blur'},
              {validator: checkMobile,trigger:'blur'}
            ]
          },
        //  控制分配角色对话框的显示和隐藏
          setRoleDialogVisible:false,
        //  当前被分配角色的用户信息
          userInfo:{},
        //  所有角色的列表
          rolesList:[],
          //已选中的角色
          selectedRoleId:''
        }
      },
      created(){
        this.getUserList()
      },
      methods: {
        async getUserList() {
          this.userList=tempuserList
          this.total=5
          return

          const {data: res} = await this.$http.get('users',{
            params: this.queryInfo
          })
         if(res.meta.status !=200){
           return this.$message.error('获取用户列表失败')
         }

         this.userList=res.data.users
         this.total=res.data.total

         console.log(res);
        },
        //监听pagesize改变事件
        handleSizeChange(newSize) {
          console.log(`每页 ${val} 条`);
          this.queryInfo.pageSize=newSize
          this.getUserList()
        },
        //监听页码值改变的事件
        handleCurrentChange(newPageNum) {
          console.log(`当前页: ${val}`);
          this.queryInfo.pageNum=newPageNum
          this.getUserList()
        },
        //状态改变
        async usestateChange(userinfo){
          console.log(userinfo)
          const {data: res}=await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
          if (res.meta.status!==200){
            userinfo.mg_state = !userinfo.mg_state
            return this.$message.error("更新用户状态失败")
          }
          this.$message.success("更新用户状态成功")
        },
      //  展示角色分配的对话框
        async setRole(userInfo){
          this.userInfo=userInfo
          //获取所有的角色列表

          // const {data: res}=await this.$http.get(`roles`)
          // if(res.meta!==200){
          //   return this.$message.info('获取角色列表失败')
          // }
          // this.rolesList=res.data
          this.rolesList=[{id:'01',roleName:'管理员'}]
          this.setRoleDialogVisible=true;
        },
      //  点击按钮，保持分配角色
        async saveRoleInfo(){
          if (!this.selectedRoleId){
            return this.$message.info('请选择一个角色')
          }

          const {data:res}=await this.$http.post(`users/${this.userInfo.id}/role`,{
            rid:this.selectedRoleId
          })

          if (res.meta!==200){
            return this.$message.error('更新角色失败')
          }
          this.$message.error('更新角色成功')

          this.getUserList();//刷新列表
          setRoleDialogVisible = false
        },
      // 关闭后重置数据
        setRoleDialogClosed(){
          this.userInfo={}
          this.selectedRoleId=''
        }

      }
    }
</script>

<style lang="less" scoped>

</style>
